package com.shakespace.algorithm.common

import com.shakespace.algorithm.binary_tree.TreeNode

/**
 * 从一个二叉树数组 构造一个二叉树根节点
 */
fun createTreeFromLevelOrder(arr: Array<Int?>): TreeNode? {
    if (arr.isEmpty()) return null

    val nodes = arr.mapIndexed { _, value ->
        if (value != null) TreeNode(value) else null
    }

    for (i in nodes.indices) {
        if (nodes[i] == null) continue

        val leftIdx = 2 * i + 1
        val rightIdx = 2 * i + 2

        if (leftIdx < nodes.size) nodes[i]?.left = nodes[leftIdx]
        if (rightIdx < nodes.size) nodes[i]?.right = nodes[rightIdx]
    }

    return nodes.getOrNull(0)
}